package com.saikuo.service.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.saikuo.service.api.ApiResultModel;
import com.saikuo.service.api.ErrorCode;
import com.saikuo.service.constant.*;
import com.saikuo.service.dao.*;
import com.saikuo.service.jpush.PushManage;
import com.saikuo.service.model.Order;
import com.saikuo.service.model.OrderDetail;
import com.saikuo.service.model.StoreInfo;
import com.saikuo.service.service.IOrderService;
import com.saikuo.service.utils.EnumUtil;
import com.saikuo.service.utils.JSONUtil;
import com.saikuo.service.vo.CouponView;
import com.saikuo.service.vo.OrderDetailView;
import com.saikuo.service.vo.OrderView;
import com.saikuo.service.vo.UserAddressView;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by shanchangyu on 16/10/18.
 */
@Service
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private IOrderDao orderDao;
    @Autowired
    private IUserDao userDao;
    @Autowired
    private IMedicineDao medicineDao;
    @Autowired
    private IStoreInfoDao storeInfoDao;
    @Autowired
    private ICouponDao couponDao;
    @Autowired
    private JpushConfig jpushConfig;

    @Override
    public ApiResultModel createOrderInfo(int userId, String name, String mobile, String address, String comments, String orderDetailParam, Integer userCouponId, Double price, Double postage, String storeCode, int payWay) {
        Order order = new Order();
        order.setUserId(userId);
        order.setName(name);
        order.setMobile(mobile);
        order.setAddress(address);
        order.setUserCouponId(userCouponId);
        order.setPrice(price);
        order.setPostage(postage);
        order.setStoreCode(storeCode);
        order.setPayWay(payWay);
        order.setComments(comments);
        Timestamp now = new Timestamp(System.currentTimeMillis());
        order.setUpdateTime(now);
        if (storeCode.isEmpty() || "0".equals(storeCode)) {
            order.setDeliveryWay(DeliveryType.MAIL.getValue());
        } else {
            order.setDeliveryWay(DeliveryType.DOOR.getValue());
        }
        if (payWay == PayType.OFFLINE.getValue()) {
            order.setStatus(OrderStatus.WAIT_DELIVERY.getValue());
        } else {
            order.setStatus(OrderStatus.WAIT_PAY.getValue());
        }
        Long orderId = orderDao.createOrderInfo(order);
        if (orderId > 0) {
            order.setOrderId(orderId);
            //插入药品详情
            JSONArray array = JSONArray.parseArray(orderDetailParam);
            List<OrderDetail> orderDetails = new ArrayList<>(array.size());
            for (int i = 0; i < array.size(); i++) {
                String jsonObject = array.getJSONObject(i).toJSONString();
                OrderDetail orderDetail = JSONUtil.jsonToBeanWithJackson(jsonObject,
                        OrderDetail.class);
                orderDetails.add(orderDetail);
            }
            orderDao.addOrderDetail(orderId, orderDetails);
            couponDao.updateUsedCoupon(userCouponId, CouponStatus.USED.getValue());
            if (OrderStatus.WAIT_DELIVERY.getValue() == order.getStatus()) {
                //推送给商户平台
                PushManage pushManage =new PushManage();
                pushManage.sendPushPlatform(jpushConfig.getPlatformAppKey(), jpushConfig.getPlatformMasterSecret(), order.getStoreCode(), orderId);
            }
            return new ApiResultModel(orderId);
        }
        return new ApiResultModel(ErrorCode.DATABASE_ERROR);
    }

    @Override
    public ApiResultModel updateOrderInfo(Long orderId, int status) {
        if (EnumUtil.getEnumByOrdinal(OrderStatus.class, status) == null) {
            return new ApiResultModel(ErrorCode.ORDER_STATUS_FAIL);
        }
        boolean result = orderDao.updateOrderInfo(orderId, status);
        if (!result) {
            return new ApiResultModel(ErrorCode.DATABASE_ERROR);
        }
        return new ApiResultModel();
    }

    @Override
    public ApiResultModel getOrderByOrderId(Long orderId) {
        OrderDetailView orderDetailView = new OrderDetailView();
        Order order = orderDao.getOrderByOrderId(orderId);
        if (order == null) {
            return new ApiResultModel(ErrorCode.ORDER_NOT_EXIST);
        } else {
            //收货信息
            UserAddressView userAddress = new UserAddressView();
            userAddress.setUserId(order.getUserId());
            userAddress.setName(order.getName());
            userAddress.setMobile(order.getMobile());
            userAddress.setAddress(order.getAddress());
            orderDetailView.setUserAddress(userAddress);
            //药品详情
            orderDetailView.setMedicine(medicineDao.getMedicineDetailByOrderId(order.getOrderId()));
            //药品其他信息
            StoreInfo storeInfo = storeInfoDao.getStoreInfoByStoreCode(order.getStoreCode());
            if (storeInfo != null) {
                orderDetailView.setStoreName(storeInfo.getName());
            } else {
                orderDetailView.setStoreName(ContextConfig.DEFAILT_STORE_NAME);
            }
            if (order.getUserCouponId() != null && order.getUserCouponId() != 0) {
                CouponView couponView = couponDao.getCouponByUserCouponId(order.getUserCouponId());
                if (couponView != null) {
                    orderDetailView.setCouponPrice(String.valueOf(couponView.getPrice()));
                }
            }
            orderDetailView.setOrderId(order.getOrderId());
            orderDetailView.setPrice(order.getPrice().toString());
            orderDetailView.setPostage(order.getPostage().toString());
            orderDetailView.setComments(order.getComments());
            orderDetailView.setStatus(order.getStatus());
            orderDetailView.setCreateTime(order.getCreateTime());
            orderDetailView.setUpdateTime(order.getUpdateTime());
            orderDetailView.setPayWay(order.getPayWay());
            orderDetailView.setDeliveryWay(order.getDeliveryWay());
        }
        return new ApiResultModel(orderDetailView);
    }

    @Override
    public ApiResultModel getOrdersByUserId(int userId, int orderStatus, int page) {
        int start = page > 0 ? page - 1 : page;
        List<Order> orders = orderDao.getOrdersByUserId(userId, orderStatus, start * ContextConfig.ORDER_PAGE_SIZE, ContextConfig.ORDER_PAGE_SIZE);
        if (CollectionUtils.isNotEmpty(orders)) {
            List<OrderView> orderViews = new ArrayList<>(orders.size());
            for (Order order : orders) {
                OrderView orderView = new OrderView();
                //药品详情
                orderView.setMedicine(medicineDao.getMedicineDetailByOrderId(order.getOrderId()));
                //药品其他信息
                StoreInfo storeInfo = storeInfoDao.getStoreInfoByStoreCode(order.getStoreCode());
                if (storeInfo != null) {
                    orderView.setStoreName(storeInfo.getName());
                } else {
                    orderView.setStoreName(ContextConfig.DEFAILT_STORE_NAME);
                }
                if (order.getUserCouponId() != null && order.getUserCouponId() != 0) {
                    CouponView couponView = couponDao.getCouponByUserCouponId(order.getUserCouponId());
                    if (couponView != null) {
                        orderView.setCouponPrice(String.valueOf(couponView.getPrice()));
                    }
                }
                orderView.setOrderId(order.getOrderId());
                orderView.setPrice(order.getPrice().toString());
                orderView.setPostage(order.getPostage().toString());
                orderView.setStatus(order.getStatus());
                orderView.setPayWay(order.getPayWay());
                orderView.setDeliveryWay(order.getDeliveryWay());
                orderView.setUpdateTime(order.getUpdateTime());
                orderViews.add(orderView);
            }
            return new ApiResultModel(orderViews);
        }
        return new ApiResultModel();
    }

    @Override
    public ApiResultModel cancelOrder(Long orderId) {
        Order order = orderDao.getOrderByOrderId(orderId);
        if (null == order) {
            return new ApiResultModel(ErrorCode.ORDER_NOT_EXIST);
        }
        boolean orderStatus = orderDao.updateOrderInfo(orderId, OrderStatus.CANCEL.getValue());
        if (order.getUserCouponId() != null && order.getUserCouponId() != 0) {
            boolean couponStatus = couponDao.updateUsedCoupon(order.getUserCouponId(), CouponStatus.NORMAL.getValue());
            if (!orderStatus && !couponStatus) {
                return new ApiResultModel(ErrorCode.DATABASE_ERROR);
            }
        }
        return new ApiResultModel();
    }

    @Override
    public ApiResultModel complainOrder(Long orderId, int userId, String phone, String content) {
        boolean orderExist = orderDao.orderExist(orderId);
        if (orderExist) {
            return new ApiResultModel(ErrorCode.ORDER_COMPLAIN_AGINE);
        }

        boolean result = orderDao.complainOrder(orderId, userId, phone, content);
        if (!result) {
            return new ApiResultModel(ErrorCode.DATABASE_ERROR);
        }
        return new ApiResultModel();
    }
}
